﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using nwrole.toolbox.sync.entity;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
using System.IO;

namespace nwrole.toolbox.OneWaySoapChannelLib.Channel
{
    public class MessageDispatcher
    {

        SyncEntityRepository repository = null;

        public MessageDispatcher(SyncEntityRepository _repository)
        {
            this.repository = _repository;
        }

        public void Send()
        {
            Guid myGuid = Guid.NewGuid();
            DateTime lockTime = DateTime.Now.AddMinutes(10);
            MessageStatusEnum status = MessageStatusEnum.Locked;

            // update top 1 SyncMessage set SessionGuid = @SessionGuid, locked = @locked, MessageStatus = @MessageStatus

            // select * from SyncMessage where SessionGuid = @SessionGuid
            SyncMessage _msg = null;

            if (1 == 1)
            {
                Send(_msg);
            }
        }

        public void Send(SyncMessage _msg)
        {

            try
            {
  /*              repository.Update(_msg, (msg) =>
                {
                    try
                    {
                        WSHttpBinding binding = new WSHttpBinding(SecurityMode.None);
                        IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection());
                        factory.Open();

                        EndpointAddress address = new EndpointAddress(msg.ServiceAddress);
                        IRequestChannel irc = factory.CreateChannel(address);
                        irc.Open();
                        MessageVersion version = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.WSAddressing10);
                        XmlReader envelopeReader = XmlReader.Create(new StringReader(msg.SoapBody));
                        Message requestMsg = Message.CreateMessage(envelopeReader, int.MaxValue, version);
                        irc.Request(requestMsg);
                        factory.Close();

                        msg.MessageStatus = MessageStatusEnum.Processed;
                        msg.LockDateTime = null;
                    }
                    catch
                    {
                        msg.MessageStatus = MessageStatusEnum.Error;
                        msg.LockDateTime = null;
                    }
                }); */

            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());
            }
        }
    }
}
